package com.jr.Controller;

import com.google.gson.Gson;
import com.jr.Pojo.Users;
import com.jr.Service.ILoginService;
import com.jr.Service.Impl.LoginServiceImpl;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

@WebServlet("/login/*")
public class LoginController extends HttpServlet {
    ILoginService ils = new LoginServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        int index = requestURI.lastIndexOf("/")+1;
        String mName=requestURI.substring(index);
        Class cla = this.getClass();
        Method method=null;
        try{
            method = cla.getMethod(mName, HttpServletRequest.class, HttpServletResponse.class);
            resp.setContentType("application/json;charset=utf-8");
            req.setCharacterEncoding("utf-8");
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        ArrayList<Users> list = ils.queryPasswordByUsername(username);
        String password1 = list.get(0).getPassword();
        String cKey = "xy;SHUPIAN66+-=+";
        String password2=null;
        try {
            password2 = LoginController.Decrypt(password1, cKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean b = false;
        if(password.equals(password2)){
            b=true;
        }
        resp.getWriter().println(new Gson().toJson(b));
    }

    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String role = req.getParameter("roles");
        if(username==""||password==""||role=="-1"){
            boolean b=false;
            resp.getWriter().println(new Gson().toJson(b));
        }else {
            String cKey = "xy;SHUPIAN66+-=+";
            String password1 = null;
            try {
                password1 = LoginController.Encrypt(password, cKey);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Users users = new Users();
            users.setUsername(username);
            users.setPassword(password1);
            users.setRole(role);
            ArrayList<Users> list = ils.queryAll();
            int index=0;
            boolean b=true;
            for(Users s:list){
                String username1 = list.get(index).getUsername();
                index++;
                if(username.equals(username1)){
                    b=false;
                    resp.getWriter().println(new Gson().toJson(b));
                    break;
                }
            }
            if(b){
                if(ils.addUsers(users)){
                    b=true;
                    resp.getWriter().println(new Gson().toJson(b));
                }else{
                    b=false;
                    resp.getWriter().println(new Gson().toJson(b));
                }
            }
        }
    }

    public void forgetPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        ArrayList<Users> list = ils.queryPasswordByUsername(username);
        String password1 = "null";
        String password2=null;
        if(list.size()==0){
            password1 = "null";
        }else{
            password1 = list.get(0).getPassword();
            String cKey = "xy;SHUPIAN66+-=+";
            try {
                password2 = LoginController.Decrypt(password1, cKey);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        resp.getWriter().println(new Gson().toJson(password2));
    }

    public void select(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String username = req.getParameter("username");
        ArrayList<Users> list = ils.queryPasswordByUsername(username);
        String role = list.get(0).getRole();
        resp.getWriter().println(new Gson().toJson(role));
    }

    //加密算法
    public static String Encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    //解密算法
    public static String Decrypt(String sSrc, String sKey) throws Exception {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }
}


